//
//  StaffSkillMatrixController.m
//  APJ Resource
//
//  Created by Richard Zhao on 2/18/14.
//  Copyright (c) 2014 APJ. All rights reserved.
//

#import "StaffSkillMatrixController.h"
#import "StaffSkillMatrix.h"
#import "SkillCategory.h"
#import "Skill.h"
#import "HRStore.h"

@implementation StaffSkillMatrixController
{
    NSArray *datas;
    NSArray *allCategory;
    NSMutableDictionary *allSkills;
}

- (id)initWithStaffId:(int)staffId
{
    self = [super init];
    
    if (self) {
        datas = [[HRStore sharedStore] skillsOfStaff:staffId];
        [self buildSkillsDictionary];
    }
    
    return self;
}

- (id)init
{
    [NSException raise:@"StaffSkillMatrix init error" format:@"please call initWithStaffId."];
    return nil;
}

- (void)buildSkillsDictionary
{
    allCategory = [[HRStore sharedStore] allSkillCategory];
    allSkills = [[NSMutableDictionary alloc] init];
    for (SkillCategory *cate in allCategory) {
        NSArray *skills = [[HRStore sharedStore] skillUnderCategory:cate.skillCategoryCode];
        [allSkills setObject:skills forKey:cate.skillCategoryCode];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return allSkills.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    SkillCategory *category = [allCategory objectAtIndex:section];
    NSArray *skills = [allSkills objectForKey:category.skillCategoryCode];
    return skills.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"StaffSkillMatrix"];
    if(cell==nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"StaffSkillMatrix"];
    }
    NSString *key = ((SkillCategory *)[allCategory objectAtIndex:indexPath.section]).skillCategoryCode;
    Skill *skill = [(NSArray *)[allSkills objectForKey:key] objectAtIndex:indexPath.row];
    cell.textLabel.text = skill.skillCode;
    
    NSPredicate *p = [NSPredicate predicateWithFormat:@"skillCode = %@", skill.skillCode];
    if ([datas filteredArrayUsingPredicate:p].count > 0) {
        [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
    } else {
        [cell setAccessoryType:UITableViewCellAccessoryNone];
    }
    
    cell.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    SkillCategory *category = [allCategory objectAtIndex:section];
    return category.skillCategoryCode;
}

@end
